package top.xmj.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xmj.dao.UserMapper;
import top.xmj.exception.BusinessException;
import top.xmj.pojo.User;
import top.xmj.service.IUserService;
import top.xmj.util.JWTUtils;
import top.xmj.util.RedisUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 冰咖啡
 * @Date:2/12/2022 下午 11:01
 * @Description: 用户服务
 */
@Service
public class UserServiceImpl implements IUserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);


    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private UserMapper usermapper;

    @Override
    public List<User> getUsers() {
//        List<User> users = usermapper.selectList(null);
        List<User> users = usermapper.getUsers();
        return users;
    }

    @Override
    public User queryByName(String name) {
        return usermapper.queryByName(name);
    }

    @Override
    public Map<String,Object> login(User u) {
        Map<String,Object> map = new HashMap<>();
        //phone是除id外的唯一标志 需要进行检查
        User user = usermapper.queryByName(u.getUsername());
        if (user == null) {
            return map;
        }
        if(!(user.getPassword().equals(u.getPassword()))){
                throw new BusinessException(405,"账号或密码错误！",null);
        }
        //将userId存入token中
        String token = JWTUtils.createToken(user.getId());
        map.put("token",token);
        user.setPassword(null);
        map.put("user",user);
        boolean res =  redisUtil.hset("token",token,user.getId(),1440);
        return map;
    }

    @Override
    public boolean addUser(User user) {
        int res = usermapper.insert(user);
        return res == 1;
    }

    @Override
    public User queryByMail(String mail) {
        return usermapper.queryByMail(mail);
    }

    @Override
    public User queryById(String id) {
        return usermapper.selectById(id);
    }

    @Override
    public int updateInfo(User user) {
        return usermapper.updateById(user);
    }

    @Override
    public User getInfoByToken(String token) {
        Map<Object, Object> m =  redisUtil.hmget("token");
        String id = (String) m.get(token);
        User user = usermapper.selectById(id);
        if(user==null){
            throw new BusinessException(405,"Token失效",null);
        }
        user.setPassword(null);
        return user;
    }

    @Override
    public void logout(String token) {
        redisUtil.hdel("token",token);
    }

}
